import {messages} from "share/common";
import React, { Component } from 'react';
import { Select } from 'antd';

const Option = Select.Option;

class ExpirationDate extends Component {
  constructor(props) {
    super(props);
    this.state = {
      month: [],
      day: [],
      conditions: [
        {
          name: messages('supplier.key483')/*月*/,
          key: 'month',
          sources: []
        },
        {
          name: messages('supplier.key484')/*日*/,
          key: 'day',
          sources: []
        }
      ]
    };
  }

  componentDidMount() {
    let { conditions } = this.state;
    conditions.map(item => {
      let limit = 12;
      item.key === 'day' ? limit = 31 : limit = 12;
      for (let i = 1; i <= limit; i++) {
        if (i < 10) {
          i = this.handleZero(i, 2);
        }
        item.sources.push(i + '');
      }
    });
    this.setState({ conditions });
  }

  handleZero = (num, n) => {
    return (Array(n).join('0') + num).slice(-n);
  };

  handleSelect = (e, index) => {
    const { onChange, value = '' } = this.props;
    let middleValue = value.split('-');
    middleValue[index] = e;
    onChange(middleValue.join('-'));
  };

  render() {
    const { disabled, value } = this.props;
    const { conditions } = this.state;
    return (
      <section className="expiration-date">
        <section className="expiration-date-grid">
          {
            conditions.map((item, index) => (
                <section>
                  <Select
                    className="expiration-date-select"
                    key={item.key}
                    value={(value || '').split('-')[index]}
                    disabled={disabled}
                    onChange={(e) => this.handleSelect(e, index)}>
                    {item.sources.map(sources => <Option value={sources}>{sources}</Option>)}
                  </Select>
                  <span>{item.name}</span>
                </section>
              )
            )
          }
        </section>
      </section>
    );
  }
}

ExpirationDate.propTypes = {
  value: React.PropTypes.string,
  onChange: React.PropTypes.func,
  disabled: React.PropTypes.bool
};

export default ExpirationDate;
